package cn.xchats.onlinetraffic.data.server.server;


import cn.xchats.onlinetraffic.common.dto.IpDto;
import cn.xchats.onlinetraffic.common.dto.UserDto;
import cn.xchats.onlinetraffic.common.dto.UserInfoDto;
import cn.xchats.onlinetraffic.common.other.service.IpService;
import cn.xchats.onlinetraffic.common.other.util.ListUtils;
import cn.xchats.onlinetraffic.common.other.util.RegularUtil;
import cn.xchats.onlinetraffic.common.other.util.StackTraceUtil;
import cn.xchats.onlinetraffic.data.server.repository.tables.Ip;
import cn.xchats.onlinetraffic.data.server.repository.tables.User;
import cn.xchats.onlinetraffic.data.server.repository.tables.Userinfo;
import cn.xchats.onlinetraffic.jooq.frame.JooqBaseService;
import cn.xchats.onlinetraffic.jooq.frame.common.MessageBean;
import cn.xchats.onlinetraffic.jooq.frame.common.BaseBean;
import org.jooq.tools.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/*
 *
 *@author teddy
 *@date 2018/5/2
 */
@Service
@SuppressWarnings("all")
public class UserService extends JooqBaseService {

    private static final String userHashKey = "user";

    private static final String[] clearField = {"passWord"};

    private static final String ipTrailKey = "-ip";//ip存储的key后缀名

   /* @Autowired
    private IpService ipService;*/

    /**
     * 注册账号
     *
     * @param userName
     * @param passWord
     * @param telephone
     * @param name
     * @param address
     * @param sex
     * @param email
     * @param qq
     * @param weChat
     * @return
     */
    public BaseBean registerUser(String userName, String passWord, String telephone, String name, String address, String sex, String email, String qq, String weChat) {
        if (StringUtils.isBlank(userName))
            return result("用户名不能为空");
        if (StringUtils.isBlank(passWord))
            return result("密码不能为空");
        List<UserDto> userDtoList = jooqStorage.dslSelect(dsl -> dsl.select().from(User.USER).where(User.USER.USERNAME.eq(userName)), UserDto.class);

        if (ListUtils.getMethods.isNotBlank(userDtoList)) {
            return result("当前账号已存在.");
        }
        UserDto userDto = new UserDto();
        userDto.setId(UUID.randomUUID().toString());
        userDto.setUserName(userName);
        userDto.setPassWord(passWord);
        userDto.setTelephone(telephone);
        userDto.setName(name);
        userDto.setAddress(address);
        userDto.setSex(sex);
        userDto.setEmail(email);
        userDto.setQq(qq);
        userDto.setWeChat(weChat);

        jooqStorage.create(User.USER, UserDto.class, userDto);
        clearResultNoNeedEntityData(userDto, clearField);
        return result(userDto);
    }

    /**
     * 用户登录
     *
     * @param userName
     * @param passWord
     * @param ip
     * @return
     */
    public BaseBean loginUser(String userName, String passWord, String ip) {
        if (StringUtils.isBlank(userName))
            return result("用户名不能为空");
        if (StringUtils.isBlank(passWord))
            return result("密码不能为空");
        List<UserDto> userDtoList = jooqStorage.listByCondition(User.USER, UserDto.class, User.USER.USERNAME.eq(userName));
        if (ListUtils.getMethods.isBlank(userDtoList)) {
            return result("账号不存在.");
        }
        UserDto user = userDtoList.get(0);
        if (!passWord.equals(user.getPassWord()))
            return result("输入密码有误");
        //添加ip记录
        IpDto taoBaoIpDto = IpService.createTaoBaoIpDto(ip);
        ipCount(user, taoBaoIpDto);
        clearResultNoNeedEntityData(user, clearField);
        return result(user);
    }

    /**
     * 添加ip记录
     *
     * @param userDto
     * @param ipDto
     */
    public void ipCount(UserDto userDto, IpDto ipDto) {
        String key = userDto.getUserName() + ipTrailKey;
        List<UserInfoDto> userInfoDtoList = jooqStorage.listByCondition(Userinfo.USERINFO, UserInfoDto.class, Userinfo.USERINFO.USERID.eq(userDto.getId()));
        UserInfoDto userInfoDto;
        if (ListUtils.getMethods.isBlank(userInfoDtoList)) {
            //加入统计
            userInfoDto = new UserInfoDto();
            userInfoDto.setId(UUID.randomUUID().toString());
            //userInfoDto.setUserName(userDto.getUserName());
            userInfoDto.setUserId(userDto.getId());
            //使用期限
            userInfoDto.setExpirationTime(RegularUtil.getMethods.getCurrentDateAfterTime(30).getTime());
            //创建userInfo
            jooqStorage.create(Userinfo.USERINFO, UserInfoDto.class, userInfoDto);
        } else {
            userInfoDto = userInfoDtoList.get(0);
        }
        ipDto.setId(UUID.randomUUID().toString());
        ipDto.setUserInfoId(userInfoDto.getId());
        ipDto.setLoginTime(new Date().getTime());
        jooqStorage.create(Ip.IP, IpDto.class, ipDto);
        //userInfoDto.setSize(userInfoDto.getSize() + 1);
        //增加计数
        System.out.println("登录用户>>" + userDto.getUserName());
    }

    /**
     * 统计用户登录次数
     *
     * @param userName
     * @return
     */
    public BaseBean countUserIp(String userName) {
        jooqStorage.listByCondition(User.USER, UserInfoDto.class, User.USER.USERNAME.eq(userName));
        jooqStorage.listByCondition(Userinfo.USERINFO, UserInfoDto.class, Userinfo.USERINFO.USERID.eq(""));
        return null;
    }

    public BaseBean updateUserSetter(String userId, String shopSort, String emailPush) {
        try {
            UserInfoDto userInfoDto = jooqStorage.listByCondition(Userinfo.USERINFO, UserInfoDto.class, Userinfo.USERINFO.USERID.eq(userId)).get(0);
            userInfoDto.setEmailPush(emailPush);
            userInfoDto.setShopSort(shopSort);

            Integer result = jooqStorage.dslUpdate(dsl -> dsl.update(Userinfo.USERINFO).set(Userinfo.USERINFO.EMAIL_PUSH, emailPush).set(Userinfo.USERINFO.SHOP_SORT, shopSort).where(Userinfo.USERINFO.USERID.eq(userId)));
            if (result > 0)
                return result(userInfoDto);
        } catch (Exception e) {
            return result(StackTraceUtil.getStackTrace(e), userId);
        }
        return result("修改失败");
    }

    public BaseBean getUserInfo(String userId) {
        List<UserInfoDto> userInfoDtos = jooqStorage.listByCondition(Userinfo.USERINFO, UserInfoDto.class, Userinfo.USERINFO.USERID.eq(userId));
        if (userInfoDtos.size() > 0) {
            UserInfoDto userInfoDto = userInfoDtos.get(0);
            userInfoDto.setExpirationTimeFormat(RegularUtil.getMethods.dateFormat(RegularUtil.FORMAT_DATE_3, new Date(userInfoDto.getExpirationTime())));
            return result(userInfoDto);
        }
        return result("无数据");
    }

    public BaseBean updateUser(String userId, String telephone, String name, String address, String sex, String email, String qq, String weChat) {

        UserDto userDto = new UserDto();
        userDto.setTelephone(telephone);
        userDto.setName(name);
        userDto.setAddress(address);
        userDto.setSex(sex);
        userDto.setEmail(email);
        userDto.setQq(qq);
        userDto.setWeChat(weChat);
        clearResultNoNeedEntityData(userDto, clearField);

        Integer result = jooqStorage.dslUpdate(dsl -> dsl.update(User.USER)
                .set(User.USER.TELEPHONE, telephone)
                .set(User.USER.NAME, name)
                .set(User.USER.ADDRESS, address)
                .set(User.USER.SEX, sex)
                .set(User.USER.EMAIL, email)
                .set(User.USER.QQ, qq)
                .set(User.USER.WECHAT, weChat)
                .where(User.USER.ID.eq(userId)));
        return result(userDto);
    }

    public BaseBean updateUserHeadPortrait(String userId, String headPortrait) {
        Integer result = jooqStorage.dslUpdate(dsl -> dsl.update(User.USER)
                .set(User.USER.HEAD_PORTRAIT, headPortrait)
                .where(User.USER.ID.eq(userId)));
        if (result > 0)
            return result(result);
        else
            return result("更换失败");
    }

}

